import os
import re
import argparse

def process_log_file(log_file_path,current_time):
    max_value = float("-inf")
    min_value = float("+inf")
    total_sum = 0
    count = 0
    time_str = ''
    #pattern: 0.01212 samples/s/p
    pattern = r"log:\d+:(\d+-\d+-\d+) .*(\d+\.\d+)( samples/s/p)  (\d+) days"
    with open(log_file_path, "r",encoding='utf-8') as file:
        for line in file:
            match = re.search(pattern, line)
            if match:
                time = match.group(1)
                if time != current_time:
                    continue
                time_str = time
                dayCount = int(match.group(4))
                if dayCount > 100:
                    continue
                value = float(match.group(2))
                max_value = max(value, max_value)
                min_value = min(value, min_value)
                total_sum += value
                count += 1
    average_value = total_sum / count if count > 0 else 0
    if time_str:
        print(f"original data(samples/s/p) at date :{time_str}    = max:{max_value:.5f}, min:{min_value:.5f}, ave:{average_value:.5f}")
    return time_str,max_value,min_value,average_value


def calc_performance(value, device_num, tokens_per_sample):
    seconds_per_day = 60 * 60 * 24
    return value * device_num * tokens_per_sample * seconds_per_day / 1000000000

def main(log_path, device_num, tokens_per_sample):
    from datetime import datetime,timedelta
    pattern = r"log:\d+:(\d+-\d+-\d+)"
    first_time = ''
    # 读取前几行，确定日志所属的日期
    with open(log_path, "r", encoding='utf-8') as file:
        for line in file:
            match = re.search(pattern, line)
            if match:
                first_time = match.group(1)
                break
    # 转换为时间，逐天计算
    now = datetime.strptime(first_time, '%Y-%m-%d')
    print("log_file:",os.path.basename(log_path))
    i = 0
    while i < 100:
        current_time = now.strftime('%Y-%m-%d')
        time_str = process_oneday(device_num, log_path, tokens_per_sample,current_time)
        if time_str == '':
            break
        # 增加1天
        now = now +  timedelta(days=1)
        i = i +1


def process_oneday(device_num, log_path, tokens_per_sample,current_time):
    time_str,max_value, min_value, average_value = process_log_file(log_path,current_time)
    max_value = calc_performance(max_value, device_num, tokens_per_sample)
    min_value = calc_performance(min_value, device_num, tokens_per_sample)
    average_value = calc_performance(average_value, device_num, tokens_per_sample)
    print(f"unit conversion as(B tokens/day) at date :{time_str}  = max:{max_value:.2f}, min:{min_value:.2f}, ave:{average_value:.2f}")
    return time_str


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="telechat parse time")
    parser.add_argument(
        "--log_path",
        default=None,
        required=False,
        help="please input log file path, log file should end with .log",
    )
    parser.add_argument(
        "--device_num",
        default=512,
        required=False,
        help="please input device num",
    )
    parser.add_argument(
        "--tokens_per_sample",
        default=8192,
        required=False,
        help="please input seq length",
    )
    args = parser.parse_args()
    main(args.log_path, int(args.device_num), int(args.tokens_per_sample))